package org.sundatagroup.aurora;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>配置. 从系统外 / 内部读取配置数据, 该部分独立于 Spring 框架外.
 * <p>系统按照如下顺序逐个读取配置数据:
 * <li>该类的同包下 conf.properties; (resource)
 * <li>工程所在目录下的 conf.properties; (file)
 * </li>
 * </p>
 * 
 * @author Zdream
 * @date 2018-04-08
 * @version 0.1.2
 * @since 0.1
 */
public class Static {
	
	private static Properties conf;
	
	static void load() {
		conf = new Properties();
		Logger logger = LoggerFactory.getLogger(Static.class.getName());
		
		try {
			loadFromResource();
		} catch (Exception e) {
			logger.warn("读取 resource 配置失败, 已忽略");
		}
		
		try {
			loadFromFile();
		} catch (Exception e) {
			logger.warn("读取 file 配置失败, 已忽略");
		}
	}
	
	private static void loadFromResource() throws Exception {
		conf.load(Static.class.getResourceAsStream("conf.properties"));
	}
	
	private static void loadFromFile() throws Exception {
		File file = new File("conf.properties");
		
		if (!file.exists()) {
			Logger logger = LoggerFactory.getLogger(Static.class.getName());
			logger.warn(String.format("配置文件: %s 不存在, 已跳过", file.getAbsolutePath()));
			return;
		}

		FileInputStream in = new FileInputStream(file);
		conf.load(in);
		
		in.close();
	}
	
	public static String getConfig(String key) {
		return conf.getProperty(key);
	}
	
	public static String getConfig(String key, String def) {
		return conf.getProperty(key, def);
	}

}
